package com.kbbywyclient.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;

import com.kbbywyclient.app.App;
import com.kbbywyclient.app.Key;
import com.kbbywyclient.callback.WeChatPayCallback;
import com.kbbywyclient.util.LogUtil;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

/**
 * Created by cbb on 2017/4/20.
 * !!!!微信支付一定要用WXPayEntryActivity这个类名，不然不能回调！！！！我花了一上午时间在这里
 * 以下为用这个类名的依据：
 *
 *
 * MicroMsg.SDK.WXApiImplV10:
 * pay, set wxappPayEntryClassname = com.tencent.mm.plugin.base.stub.WXPayEntryActivity
 *
 *
 *
 */

public class WXPayEntryActivity extends Activity implements IWXAPIEventHandler {
    private IWXAPI iwxapi;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        iwxapi= WXAPIFactory.createWXAPI(this, Key.weChatAppId,false);
        registerCallback();
    }

    private void registerCallback(){
        try{
            boolean suc=iwxapi.handleIntent(getIntent(),this);
            LogUtil.d("注册回调结果:"+suc);
        }catch (Exception e){
            LogUtil.d(e.getMessage());
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        registerCallback();
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        WeChatPayCallback payCallback = App.getInstance().weChatPayCallback;
        //微信支付回调
        if(baseResp.getType()== ConstantsAPI.COMMAND_PAY_BY_WX) {
            switch (baseResp.errCode) {
                case BaseResp.ErrCode.ERR_COMM:
                    //支付失败
                    if(payCallback!=null){
                        payCallback.onWeChatPayFailure();
                    }
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    //用户取消支付
                    if(payCallback!=null){
                        payCallback.onWeChatPayCancel();
                    }
                    break;
                case BaseResp.ErrCode.ERR_OK:
                    //支付成功
                    if(payCallback!=null){
                        payCallback.onWeChatPaySuccess();
                    }
                    break;
            }
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
